import json
from utils import log_info, log_exception, log_error, log_debug
from services.importers.base_importer import BaseImporter


class JSONImporter(BaseImporter):
    """JSON文件导入器"""

    def read_file(self, file_path, progress_var=None, progress_label=None, import_dialog=None):
        """读取JSON文件并解析为题目数据"""
        try:
            log_debug(f"开始处理JSON文件: {file_path}")
            # 读取JSON文件
            with open(file_path, 'r', encoding='utf-8') as f:
                try:
                    questions = json.load(f)
                    if not isinstance(questions, list):
                        raise ValueError("题库文件格式不正确，应为JSON数组")
                    total = len(questions)
                    if total == 0:
                        raise ValueError("题库文件为空")
                except json.JSONDecodeError:
                    log_error(f"JSON格式错误，无法解析: {file_path}")
                    raise ValueError("JSON格式错误，无法解析")

            # 处理空值并格式化数据
            formatted_questions = []
            for q in questions:
                # 检查必要字段
                required_fields = ['Q', 'A', 'B', 'C', 'D', 'T', 'F', 'type']
                if not all(key in q for key in required_fields):
                    continue

                # 处理空值
                for key in q:
                    if q[key] is None:
                        q[key] = ''

                # 格式化数据
                formatted_q = {
                    'J': q.get('J', ''),
                    'P': q.get('P', ''),
                    'I': q.get('I', ''),
                    'Q': q.get('Q', ''),
                    'T': q.get('T', ''),
                    'A': q.get('A', ''),
                    'B': q.get('B', ''),
                    'C': q.get('C', ''),
                    'D': q.get('D', ''),
                    'F': q.get('F', ''),
                    'LA': q.get('LA', ''),
                    'LB': q.get('LB', ''),
                    'LC': q.get('LC', ''),
                    'type': q.get('type', 0)
                }
                formatted_questions.append(formatted_q)

            return formatted_questions
        except Exception as e:
            log_exception(f"处理JSON数据时发生异常: {str(e)}")
            return []


def process_json_data(file_path, progress_var=None, progress_label=None, import_dialog=None):
    """处理JSON数据并导入数据库"""
    importer = JSONImporter()
    return importer.process_data(file_path, progress_var, progress_label, import_dialog)